package dyl.sys.action;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;

import dyl.common.util.DylSqlUtil;
import dyl.common.util.JdbcTemplateUtil;
import dyl.sys.util.FileUtils;

@Controller
public class UploadAction extends BaseAction {
	@Resource
	private JdbcTemplateUtil jdbcTemplate;
	//依赖包 commons-fileupload-1.3.1.jar
	@RequestMapping("/upload.do")
	public void upload(HttpServletRequest request,HttpServletResponse response) throws Exception {
		JSONObject json = new JSONObject();
		// 这里我用到了jar包
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile((String) iter.next());
					if (file != null) {
						String fileName = file.getOriginalFilename();
						String realName = FileUtils.diskNameProductor(fileName);
						saveFileFromInputStream(file.getInputStream(),realName);
						String sql = "insert into sys_fileinfo(id, real_name, upload_name, file_size, file_url,creator) values("+DylSqlUtil.getnextSeqNextVal()+",?,?,?,?,?)";
						jdbcTemplate.update(sql,new Object[]{realName,fileName,file.getSize(),"dowload.do?real_name="+realName+"&upload_name="+fileName,getSysUser(request).getId()});
						json.put("result", true);
						json.put("realName", realName);
						json.put("size", file.getSize());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("result", false);
		}
		response.getWriter().print(json.toJSONString());
	}
	private void saveFileFromInputStream(InputStream stream,String filename) throws IOException{
		FileUtils.filePathMaker();
        FileOutputStream fs=new FileOutputStream(FileUtils.filePathProductor(filename));
        byte[] buffer =new byte[1024*1024];
        int byteread = 0; 
        while ((byteread=stream.read(buffer))!=-1)
        {
           fs.write(buffer,0,byteread);
           fs.flush();
        } 
        fs.close();
        stream.close();      
    }
}
